package com.libs.xxf.pay_module.pay;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.libs.xxf.pay_module.R;
import com.libs.xxf.pay_module.utils.OrderInfoUtil2_0;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tools.xxf.configlib.config.ConfigKeys;

import org.json.JSONObject;

import java.util.Map;


/**
 * Created by 傅令杰
 */

public class FastPay implements View.OnClickListener {

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2016082600314465";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088312555873221";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static final String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE =
            "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCVFofO9bh8cG745TRJoN9eoDOCzOmTyb7j5LkqfMNTaME35czhrvjdB73pwti1EmGPV503XjVkP0lYawU4IcEN2yOV882QxrhS917g4F/2GlIgDZBbJpHzIK4UI2eNhhJr3/996svffi284i7ImYcCJKcILFGuQmTZhn/FMN6xzS3t7lmPRtDFj/x5tmPmCdvTfy313i+z3wqsqYZO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a9qw2iU1DALaGpoi6z9wxiTFpJtBiDW4D/hEoKhZ3p/0FdwnLHMcyTMgbzA+r8J3tuECpm3mCcI8uxg0vjLfhhDJOUHPxj+ujFj8BQzrujVU465nkCgYAJxizOrUsvbnJTt2uib49qmFm7wMhLjTySphSAg5DZm8Wp4lNhKgM/kuAtKVnLH3G/l2T8l1/eS3BmnDH0e//8MmdSmaEOhD+eu15zQ9MbFj4GUxDDeVm71AXj5CpYxdkFnPawrYy+qfAD/6i/fyk+FJzJekDV7XozYKYsttpoog==";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    // APP_ID 替换为你的应用从官方网站申请到的合法appId
    public static final String APP_ID = "wxd930ea5d5a258f4f";

    //设置支付回调监听
    private IAlPayResultListener mIAlPayResultListener = null;
    private Activity mActivity = null;

    private AlertDialog mDialog = null;
    private int mOrderID = -1;

    private FastPay(Activity mActivity) {
        this.mActivity = mActivity;
        this.mDialog = new AlertDialog.Builder(mActivity).create();
    }

    public static FastPay create(Activity mActivity) {
        return new FastPay(mActivity);
    }

    public void beginPayDialog() {
        mDialog.show();
        final Window window = mDialog.getWindow();
        if (window != null) {
            window.setContentView(R.layout.dialog_pay_panel);
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.anim_panel_up_from_bottom);
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            //设置属性
            final WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
            window.setAttributes(params);

            window.findViewById(R.id.btn_dialog_pay_alpay).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_wechat).setOnClickListener(this);
            window.findViewById(R.id.btn_dialog_pay_cancel).setOnClickListener(this);
        }
    }

    public FastPay setPayResultListener(IAlPayResultListener listener) {
        this.mIAlPayResultListener = listener;
        return this;
    }

    public FastPay setOrderId(int orderId) {
        this.mOrderID = orderId;
        return this;
    }

    /**
     * 支付宝支付
     *
     * @param orderId :商品id
     */
    private void alPay(int orderId) {
        /////服务器干的事///////////////////////////////
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty
                (RSA_PRIVATE))) {
            new android.app.AlertDialog.Builder(mActivity).setTitle("警告").setMessage("需要配置APPID | " +
                    "RSA_PRIVATE")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialoginterface, int i) {
                            //
                            mActivity.finish();
                        }
                    }).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;
        Logger.d("PAY_SIGN", orderInfo);
        /////服务器干的事///////////////////////////////



        //必须是异步的调用客户端支付接口
        final PayAsyncTask payAsyncTask = new PayAsyncTask(mActivity, mIAlPayResultListener);
        payAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, orderInfo);

    }

    /**
     * 微信支付
     *
     * @param orderId
     */
    private void weChatPay(int orderId) {
        final String weChatPrePayUrl = "你的服务端微信预支付地址" + orderId;
        Logger.d("WX_PAY", weChatPrePayUrl);

        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(mActivity, null);
        iwxapi.registerApp(APP_ID);

                        final String prepayId =     "服务器返回的组装的参数" ;//  result.getString("prepayid");
                        final String partnerId =    "服务器返回的组装的参数" ;//  result.getString("partnerid");
                        final String packageValue = "服务器返回的组装的参数" ;//  result.getString("package");
                        final String timestamp =    "服务器返回的组装的参数" ;//  result.getString("timestamp");
                        final String nonceStr =     "服务器返回的组装的参数" ;//  result.getString("noncestr");
                        final String paySign =      "服务器返回的组装的参数" ;//  result.getString("sign");

                        final PayReq payReq = new PayReq();
                        payReq.appId = APP_ID;
                        payReq.prepayId = prepayId;
                        payReq.partnerId = partnerId;
                        payReq.packageValue = packageValue;
                        payReq.timeStamp = timestamp;
                        payReq.nonceStr = nonceStr;
                        payReq.sign = paySign;

                        iwxapi.sendReq(payReq);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_dialog_pay_alpay) {
            alPay(mOrderID);
            mDialog.cancel();
        } else if (id == R.id.btn_dialog_pay_wechat) {
            weChatPay(mOrderID);
            mDialog.cancel();
        } else if (id == R.id.btn_dialog_pay_cancel) {
            mDialog.cancel();
        }
    }
}
